<template>
  <div class="uploadImg">
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :http-request="httpRequest"
    >
      <img
        v-if="value"
        :src="value"
        class="avatar"
        @click.stop.prevent="isShow = true"
      >
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
    <div v-if="value" class="del" @click="del">X</div>
    <el-dialog title="图片预览" width="500px" :visible.sync="isShow">
      <img :src="value" style="width: 100%">
    </el-dialog>
    <el-progress v-if="loading" :percentage="percentage" />
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKID50f3AzYqqZ1C6j5C2cwzmHVTAajbCWZL',
  SecretKey: 'Yqrb5IEtGUR7WfX7QTFfolSs1tUpse9O'
})
export default {
  name: 'UploadImg',
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      loading: false,
      percentage: 0,
      isShow: false
    }
  },
  methods: {
    beforeAvatarUpload(file) {
      console.log('beforeAvatarUpload', file)
      const isPng = file.type === 'image/png'
      if (!isPng) {
        this.$message.error('请上传image格式或png格式的图片')
      }
      return isPng
    },
    handleAvatarSuccess(res, file) {
      console.log(res, file)
    },
    httpRequest(res) {
      this.loading = true
      this.percentage = 0
      cos.putObject(
        {
          Bucket: 'hr77-1308949889' /* 必须 */,
          Region: 'ap-nanjing' /* 存储桶所在地域，必须字段 */,
          Key: res.file.uid + '' /* 必须 */,
          StorageClass: 'STANDARD',
          Body: res.file, // 上传文件对象
          onProgress: (progressData) => {
            this.percentage = progressData.percent * 100
            if (progressData.percent === 1) {
              setTimeout(() => {
                this.loading = false
              }, 1000)
            }
            console.log(JSON.stringify(progressData))
          }
        },
        (err, data) => {
          console.log(err || data)
          this.$emit('input', 'http://' + data.Location)
        }
      )
    },
    del() {
      this.$emit('input', '')
    }
  }
}
</script>

<style lang="scss" scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.uploadImg {
  position: relative;
  width: 178px;
  &:hover {
    .del {
      display: block;
    }
  }
  .del {
    position: absolute;
    top: 10px;
    right: 10px;
    cursor: pointer;
    display: none;
  }
}
</style>
